﻿using DevelopAssistant.Service;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.WinFormsUI.Docking;
using ICSharpCode.WinFormsUI.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DevelopAssistant.AddIn.SQLProfesser
{
    public partial class MainForm : DockContent
    {       
        bool isThreadBusy = false;
        string assemblyPath = string.Empty;
        string connectionString = string.Empty;       
        TreeNode LastCheckedNode = null;

        BaseForm _MainForm = null;

        public MainForm()
        {
            InitializeComponent();
            InitializeControls();
        }

        public MainForm(BaseForm baseForm, DockPanel panel)
            : this()
        {
            toolStripButtonOpen.Enabled = true;
            toolStripButtonSave.Enabled = true;
            _MainForm = baseForm;
        }

        private void InitializeControls()
        {
            connectionString = "Server=192.168.0.116;Initial Catalog=CMSGroupSet;User ID=sa;Pwd=YHPych920,.;";
            
            textEditorControl1.ShowEOLMarkers = false;
            textEditorControl1.ShowHRuler = false;
            textEditorControl1.ShowInvalidLines = false;
            textEditorControl1.ShowMatchingBracket = true;
            textEditorControl1.ShowSpaces = false;
            textEditorControl1.ShowTabs = false;
            textEditorControl1.ShowVRuler = false;
            textEditorControl1.AllowCaretBeyondEOL = false;
            textEditorControl1.SetHighlighting("Default", "TSQL");
            //textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("Default", "TSQL");
            //textEditorControl1.Encoding = Encoding.GetEncoding("GB2312");

            panel1.BorderColor = SystemColors.ControlDarkDark;

            assemblyPath = string.Format("{0}\\AddIn\\{1}", AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'), "DevelopAssistant.SQLProfesser.AddIn"); //DevelopAssistant.AddIn.SQLProfesser
            //DevelopAssistant.Common.NLogger.BaseDirectory = string.Format("{0}\\Logger", AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'));

        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            if (this.IsHandleCreated)
            {
                if (this.NProgressBar != null)
                {
                    this.NProgressBar.Location = new Point((this.textEditorControl1.Width - this.NProgressBar.Width) / 2,
                        (this.textEditorControl1.Height - this.NProgressBar.Height) / 2);
                }
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            LoadConfigure();
            LoadTreeview();
        }

        private void LoadTreeview()
        {
            if (!isThreadBusy)
            {
                isThreadBusy = true;               
                System.Threading.Thread thread =
                    new System.Threading.Thread(LoadTreeview_Handler);
                thread.IsBackground = true;
                thread.Start();
            }
            else
            {
                MessageBox.Show(this,"系统正忙，请稍候再试...","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        private void LoadTreeview_Handler()
        {
            if (zTreeview.InvokeRequired)
            {
                zTreeview.Invoke(new MethodInvoker(delegate()
                {
                    toolStripStatusLabel2.Text = "开始加载树";
                    zTreeview.Nodes.Clear();
                }));
            }
            else
            {
                toolStripStatusLabel2.Text = "开始加载树";
                zTreeview.Nodes.Clear();
            }
            try
            {
                using (var db = NORM.DataBase.DataBaseFactory.Create(connectionString, NORM.DataBase.DataBaseTypes.SqlDataBase))
                {
                    LoadTreeview_Node(db, null);
                }
                if (zTreeview.InvokeRequired)
                {
                    zTreeview.Invoke(new MethodInvoker(delegate()
                    {
                        zTreeview.ExpandAll();
                        toolStripStatusLabel2.Text = "完成";
                    }));
                }
                else
                {
                    zTreeview.ExpandAll();
                    toolStripStatusLabel2.Text = "完成";
                }
            }
            catch (Exception ex)
            {
                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
                if (zTreeview.InvokeRequired)
                {
                    zTreeview.Invoke(new MethodInvoker(delegate()
                    {
                        zTreeview.ExpandAll();
                        toolStripStatusLabel2.Text = ex.Message;
                    }));
                }
                else
                {
                    zTreeview.ExpandAll();
                    toolStripStatusLabel2.Text = ex.Message;
                }
            }
            isThreadBusy = false;
        }

        private void LoadTreeview_Node(NORM.DataBase.DataBase db, TreeViewNode node)
        {
            string sql = string.Empty;
            if (node == null)
            {
                sql = "SELECT [NodeID] ,[NodeName] ,[NodeType] ,[NodeDescription] ,[AlarmSeverity] ,[ParentNodeID] ,[NodeSequence] ,[RefreshTime] ,[NodeCode] ,[ServerAddr] ,[DataBaseName] ,[DataPsd] ,[DataUser] ,[DataName] FROM [CMSGroupSet].[dbo].[TreeGroup] WHERE ParentNodeID = - 1 ";
            }
            else
            {
                sql = "SELECT [NodeID] ,[NodeName] ,[NodeType] ,[NodeDescription] ,[AlarmSeverity] ,[ParentNodeID] ,[NodeSequence] ,[RefreshTime] ,[NodeCode] ,[ServerAddr] ,[DataBaseName] ,[DataPsd] ,[DataUser] ,[DataName] FROM [CMSGroupSet].[dbo].[TreeGroup] WHERE ParentNodeID = "+node.NodeId+" ";
            }

            var data = db.QueryTable(sql, null);

            if (node == null)
            {
                foreach (DataRow row in data.Rows)
                {
                    TreeViewNode treenode = new TreeViewNode();
                    treenode.ImageIndex = 1;
                    treenode.SelectedImageIndex = treenode.ImageIndex;
                    treenode.Name = row["NodeID"].ToString().Trim();
                    treenode.NodeId = Convert.ToInt32(row["NodeID"]);
                    treenode.Text = row["NodeName"].ToString().Trim();
                    this.zTreeview.Invoke(new MethodInvoker(delegate() {
                        this.zTreeview.Nodes.Add(treenode);
                    }));
                    LoadTreeview_Node(db, treenode);
                }
            }
            else
            {
                foreach (DataRow row in data.Rows)
                {
                    TreeViewNode treenode = new TreeViewNode();                    
                    if (node.Level == 1)
                    {
                        treenode.ImageIndex = 2;
                    }
                    else
                    {
                        treenode.ImageIndex = 1;
                    }
                    treenode.SelectedImageIndex = treenode.ImageIndex;
                    treenode.Name = row["NodeID"].ToString().Trim();
                    treenode.NodeId = Convert.ToInt32(row["NodeID"]);
                    treenode.Text = row["NodeName"].ToString().Trim();
                    treenode.Server = row["ServerAddr"]+"";
                    treenode.UserID = row["DataUser"] + "";
                    treenode.Password = row["DataPsd"]+"";
                    treenode.ConfigureDataBase = row["DataBaseName"] + "";
                    treenode.MeasureDataBase = row["DataName"] + "";
                    this.zTreeview.Invoke(new MethodInvoker(delegate()
                    {
                        node.Nodes.Add(treenode);
                    }));
                    LoadTreeview_Node(db, treenode);
                }
            }

        }

        private void zTreeview_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            e.Node.ImageIndex = 0;
            e.Node.SelectedImageIndex = e.Node.ImageIndex;
        }

        private void zTreeview_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.ImageIndex = 1;
            e.Node.SelectedImageIndex = e.Node.ImageIndex;
        }

        private void zTreeview_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeNode node = e.Node;
                zTreeview.SelectedNode = e.Node;
                LastCheckedNode = node;
            }
        }

        private void zTreeview_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeViewNode node = (TreeViewNode)e.Node;
            if (node.Level == 2)
            {
                NORM.Common.ConnectionString connection = new NORM.Common.ConnectionString();
                connection.DataBaseName = node.ConfigureDataBase;
                connection.Server = node.Server;
                connection.UserId = node.UserID;
                connection.Password = node.Password;

                using (var db = NORM.DataBase.DataBaseFactory.Create(connection.connectionString, NORM.DataBase.DataBaseTypes.SqlDataBase))
                {
                    string Message=string.Empty;
                    if (db.TestConnect(out Message))
                    {
                        string sql = "SELECT [NodeID] ,[NodeName] ,[NodeType] ,[NodeDescription] ,[AlarmSeverity] ,[ParentNodeID] ,[NodeSequence] ,[RefreshTime] ,[Active] ,[HasChild] ,[Diagram] ,[OutCode]  ";
                        sql += "FROM [TreeStructure] WHERE [NodeType]='设备' ";
                        sql += "ORDER BY [NodeName] ASC ";
                        var data = db.QueryTable(sql, null);

                        if (data.Rows.Count > 0)
                        {                           
                            if (node.Nodes.Count <= 0)
                            {
                                foreach (DataRow row in data.Rows)
                                {
                                    TreeViewNode nde = new TreeViewNode();
                                    nde.ImageIndex = 3;
                                    nde.SelectedImageIndex = nde.ImageIndex;
                                    nde.NodeId = Convert.ToInt32(row["NodeID"] + "");
                                    nde.Text = row["NodeName"] + "";
                                    node.Nodes.Add(nde);
                                }

                                node.Expand();

                                e.Node.ImageIndex = 1;
                                e.Node.SelectedImageIndex = e.Node.ImageIndex;
                            }                        
                        } 
                    }
                    else
                    {
                        MessageBox.Show(this, Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }               

                }
            }
        }

        private void zTreeview_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse)
            {
                TreeNode node = e.Node;
                zTreeview.SelectedNode = e.Node;                
                zTreeview_NodeChildrenHandle(node);
                zTreeview_NodeParentHandle(node);               
                LastCheckedNode = node;
            }
        }

        private void zTreeview_NodeChildrenHandle(TreeNode node)
        {
            foreach (TreeNode nde in node.Nodes)
            {
                nde.Checked = node.Checked;
                zTreeview_NodeChildrenHandle(nde);
            }
        }

        private void zTreeview_NodeParentHandle(TreeNode node)
        {
            if (node.Parent != null)
            {
                if (node.Checked)
                {
                    node.Parent.Checked = node.Checked;
                }
                if (!node.Checked)
                {
                    bool allunchecked = true;
                    foreach (TreeNode nde in node.Parent.Nodes)
                    {
                        if (nde.Checked)
                        {
                            allunchecked = false;
                            break;
                        }
                    }
                    if (allunchecked)
                    {
                        node.Parent.Checked = false;
                    }
                }
                zTreeview_NodeParentHandle(node.Parent);
            }            
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            ExecuteCommand();
        }

        private void toolStripButtonRefresh_Click(object sender, EventArgs e)
        {
            LoadTreeview();
        }

        private void toolStripButtonConnectionSetting_Click(object sender, EventArgs e)
        {
            SettingsForm form = new SettingsForm(this.connectionString);
            if (this._MainForm != null)
            {
                form.Text = _MainForm.Text;
                form.XTheme = _MainForm.XTheme;
            }
            if (form.ShowDialog(this).Equals(DialogResult.OK))
            {
                this.connectionString = form.ConnectionString.ToString();
                SaveConfigure();
            }
        }

        private void toolStripButtonSQLFormat_Click(object sender, EventArgs e)
        {
            string sql = this.textEditorControl1.Text;
            textEditorControl1.Text = "格式化中...";
            System.Threading.Thread th = new System.Threading.Thread(() => {
                string sqlformat = DevelopAssistant.Format.TsqlFormatHelper.FormatToTSQL(sql, AppSettings.EditorSettings.KeywordsCase);
                this.Invoke(new MethodInvoker(delegate() { textEditorControl1.Text = sqlformat; }));
            });
            th.IsBackground = true;
            th.Start();
        }

        private void LoadConfigure()
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load(assemblyPath);
            try
            {
                var element = xmlDoc.SelectSingleNode("//ConnectionString");
                if (element != null)
                {
                    string value =element.InnerText;
                    connectionString = NORM.Common.DEncrypt.Decrypt(value, "#ZB@8741Z");
                }               
            }
            catch (Exception ex)
            {

            }

        }

        private void SaveConfigure()
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load(assemblyPath);
            try
            {
                var element = xmlDoc.SelectSingleNode("//ConnectionString");
                if (element != null)
                {
                    string value =  NORM.Common.DEncrypt.Encrypt(connectionString, "#ZB@8741Z");
                    element.InnerText = value;
                }
                xmlDoc.Save(assemblyPath);
            }
            catch (Exception ex)
            {

            }
        }

        private void ExecuteCommand()
        {
            if (!isThreadBusy)
            {
                string CommandText = this.textEditorControl1.ActiveTextAreaControl.SelectionManager.SelectedText;
                if (string.IsNullOrEmpty(CommandText))
                {
                    CommandText = this.textEditorControl1.ActiveTextAreaControl.Document.TextContent;
                }

                if (string.IsNullOrEmpty(CommandText))
                {
                    isThreadBusy = false;
                    MessageBox.Show(this, "SQL命令文本不能为空", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (!chkConfigure.Checked && !chkMeasureData.Checked)
                {
                    isThreadBusy = false;
                    MessageBox.Show(this, "请先选择要执行的数据库类型", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                isThreadBusy = true;
                NProgressBar.Visible = true;
                progressBar1.Value = 0;
                label1.Text = "任务开始执行 校验中...";

                System.Threading.Thread th =
                    new System.Threading.Thread(delegate() { ExecuteCommand_Handler(CommandText); });

                th.IsBackground = true;
                th.Start();

            }
            else
            {
                MessageBox.Show(this,"系统正忙，请稍候再试","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        private void ExecuteCommand_Handler(string sql)
        {
            int zcount = 0;
            foreach (TreeNode node in this.zTreeview.Nodes)
            {
                foreach (TreeNode node2 in node.Nodes)
                {
                    foreach (TreeNode node3 in node2.Nodes)
                    {
                        if (node3.Checked)
                        {
                            zcount++;
                        }
                    }
                }
            }

            if (chkConfigure.Checked && chkMeasureData.Checked)
            {
                zcount = zcount * 2;
            }

            int index = 0; double value = 0;
            NProgressBar.Invoke(new MethodInvoker(delegate() { label1.Text = "已完成: " + index + " / " + zcount; }));

            foreach (TreeViewNode node in this.zTreeview.Nodes)
            {
                foreach (TreeViewNode node2 in node.Nodes)
                {
                    foreach (TreeViewNode node3 in node2.Nodes)
                    {
                        if (node3.Checked)
                        {
                            if (chkConfigure.Checked)
                            {
                                index++;
                                value = index * 1.0 / zcount * 100;

                                NORM.Common.ConnectionString connect = new NORM.Common.ConnectionString();
                                connect.Server = node3.Server;
                                connect.UserId = node3.UserID;
                                connect.Password = node3.Password;
                                connect.DataBaseName = node3.ConfigureDataBase;
                                ExceuteTSQL(connect, sql);                               

                                NProgressBar.Invoke(new MethodInvoker(delegate()
                                {
                                    label1.Text ="已完成: "+ index + " / " + zcount;
                                    progressBar1.Value = (int)value;
                                }));
                            }
                            if (chkMeasureData.Checked)
                            {
                                index++;
                                value = index * 1.0 / zcount * 100;

                                NORM.Common.ConnectionString connect = new NORM.Common.ConnectionString();
                                connect.Server = node3.Server;
                                connect.UserId = node3.UserID;
                                connect.Password = node3.Password;
                                connect.DataBaseName = node3.MeasureDataBase;
                                ExceuteTSQL(connect, sql);  

                                NProgressBar.Invoke(new MethodInvoker(delegate()
                                {
                                    label1.Text = "已完成: " + index + " / " + zcount;
                                    progressBar1.Value = (int)value;
                                }));
                            }
                        }
                    }
                }
            }


            isThreadBusy = false;
            NProgressBar.Invoke(new MethodInvoker(delegate()
            {
                NProgressBar.Visible = false;
            }));
        }

        private void ExceuteTSQL(NORM.Common.ConnectionString conn,string sql)
        {
            string Message = string.Empty;
            if (string.IsNullOrEmpty(conn.Server))
            {
                return;
            }
            if (string.IsNullOrEmpty(conn.DataBaseName))
            {
                return;
            }
            using (var db = NORM.DataBase.DataBaseFactory.Create(conn.ToString(),NORM.DataBase.DataBaseTypes.SqlDataBase))
            {
                var connected = db.TestConnect(out Message);
                if (connected)
                {
                    try
                    {  
                        
                        var SqlCommands = System.Text.RegularExpressions.Regex.Split(
                            sql //System.Text.RegularExpressions.Regex.Replace(sql, "[\r\n|\r|\n]+", "\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase)                          
                            , @"\r\n\s*go", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                        foreach (var command in SqlCommands)
                        {
                            string commandText = System.Text.RegularExpressions.Regex.Replace(command, "/\\*.*\\*/", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            commandText = System.Text.RegularExpressions.Regex.Replace(commandText.Replace("数据库名", conn.DataBaseName), "[\r\n|\r|\n]+", "\r\n", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            if (!string.IsNullOrEmpty(commandText.Replace("\r\n","").Trim()))
                            {
                                db.Execute(CommandType.Text, commandText, null);
                            }
                        }

                        //db.Execute(CommandType.Text, sql, null);
                    }
                    catch (Exception ex)
                    {
                        //记录日志
                        DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "系统错误", DateTime.Now, ex.Source, ex.StackTrace);
                        this.Invoke(new MethodInvoker(() => { ICSharpCode.WinFormsUI.Forms.MessageForm.Show(this._MainForm, ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); }));
                    }
                }
            }           
        }

        private void toolStripButtonRebuild_Click(object sender, EventArgs e)
        {
            RebuildIndxes();
        }

        private void RebuildIndxes()
        {
            int checkedNodesCount = 0;
            foreach (TreeViewNode node1 in this.zTreeview.Nodes)
            {
                foreach (TreeViewNode node2 in node1.Nodes)
                {
                    foreach (TreeViewNode node3 in node2.Nodes)
                    {
                        if (node3.Checked)
                        {
                            checkedNodesCount++;
                        }
                    }
                }
            }

            if (checkedNodesCount > 0)
            {
                isThreadBusy = true;
                NProgressBar.Visible = true;
                progressBar1.Value = 0;
                label1.Text = "任务开始执行 校验中...";

                System.Threading.Thread th = new System.Threading.Thread(() =>
                {
                    var result = RebuildIndexes_Handler(checkedNodesCount);

                    isThreadBusy = false;
                    NProgressBar.Invoke(new MethodInvoker(delegate()
                    {
                        label1.Text = "任务执行完成 详细信息请查看日志";
                        NProgressBar.Visible = false;
                    }));

                });
                th.IsBackground = true;
                th.Start();

            }
            else
            {
                MessageBox.Show(this, "请左侧选择风场节点", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private bool RebuildIndexes_Handler(int zcount)
        {
            int index = 0;
            foreach (TreeViewNode node1 in this.zTreeview.Nodes)
            {
                foreach (TreeViewNode node2 in node1.Nodes)
                {
                    foreach (TreeViewNode node3 in node2.Nodes)
                    {
                        if (node3.Checked)
                        {
                            NORM.Common.ConnectionString connect = new NORM.Common.ConnectionString();
                            connect.Server = node3.Server;
                            connect.UserId = node3.UserID;
                            connect.Password = node3.Password;
                            connect.DataBaseName = node3.MeasureDataBase;
                            RebuildIndexesTSQL(connect);

                            index++;
                            double value = index * 1.0 / zcount * 100;
                            NProgressBar.Invoke(new MethodInvoker(delegate() {

                                progressBar1.Value = (int)value;
                                label1.Text = "任务开始执行 已完成 " + index + " / " + zcount;
                            
                            }));

                        }
                    }
                }
            }
            return true;
        }

        private void RebuildIndexesTSQL(NORM.Common.ConnectionString conn)
        {
            using (var db = NORM.DataBase.DataBaseFactory.Create(conn.ToString(), NORM.DataBase.DataBaseTypes.SqlDataBase))
            {
                string message=string.Empty;
                if(db.TestConnect(out message))
                {
                    string sql = "SELECT Name FROM SysObjects Where XType='U' ";
                    sql += "AND ( Name LIKE 'MeasureValues_%' OR  Name LIKE 'WaveData_%') ";
                    sql += "ORDER BY Name ";
                    var data = db.QueryTable(sql);

                    int timeout = 2 * 60;

                    foreach (DataRow row in data.Rows)
                    {
                        string name = (row["Name"] + "").Trim();

                        if (name.Equals("MeasureValuesA", StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        try
                        {
                            string command = "DROP INDEX [IX_" + name + "] ON [dbo].[" + name + "] ";
                            db.Execute(CommandType.Text,command,null);

                            if (name.StartsWith("WaveData", StringComparison.OrdinalIgnoreCase))
                            {
                                command = "DROP INDEX [PK_" + name + "] ON [dbo].[" + name + "] ";
                                db.Execute(CommandType.Text, command, null);
                            }

                            DevelopAssistant.Common.NLogger.WriteToLine("表 [" + name + "] 删除索引成功", "DevelopAssistant.AddIn.SQLProfesser", DateTime.Now, "", "");

                        }
                        catch (Exception ex)
                        {
                            DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "DevelopAssistant.AddIn.SQLProfesser", DateTime.Now, ex.Source, ex.StackTrace);
                        }

                        try
                        {
                            string command = "CREATE NONCLUSTERED INDEX [IX_" + name + "] ON [dbo].[" + name + "] ";

                            if (name.StartsWith("MeasureValues", StringComparison.OrdinalIgnoreCase))
                            {
                                command += "( [Datetime] DESC ) ";
                            }
                            else
                            {
                                command += "( [DateTime] DESC,[NodeID] ASC,[ParaID] ASC ) ";
                            }

                            command += "WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ";
                            db.Execute(CommandType.Text, command, null);

                            DevelopAssistant.Common.NLogger.WriteToLine("表 [" + name + "] 创建索引成功", "完成", DateTime.Now, "DevelopAssistant.AddIn.SQLProfesser");

                        }
                        catch (Exception ex)
                        {
                            DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
                        }

                    }
                }
            }
        }

        private void toolStripButtonOpen_Click(object sender, EventArgs e)
        {
            var openfiledlg = new OpenFileDialog();
            openfiledlg.Filter = "sql脚本|*.sql|text文本|*.txt";
            if (openfiledlg.ShowDialog(this).Equals(DialogResult.OK))
            {
                if (!string.IsNullOrEmpty(openfiledlg.FileName))
                {
                    string filePath = openfiledlg.FileName;
                    string content = string.Empty;
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath,System.Text.Encoding.Default))
                    {
                        content = sr.ReadToEnd();
                    }
                    this.textEditorControl1.Text = content;
                }
            }

            
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            var savefiledlg = new SaveFileDialog();
            savefiledlg.Filter = "sql脚本|*.sql";
            if (savefiledlg.ShowDialog(this).Equals(DialogResult.OK))
            {
                if (!string.IsNullOrEmpty(savefiledlg.FileName))
                {
                    string savePath = savefiledlg.FileName;
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savePath, false, System.Text.Encoding.Default))
                    {
                        sw.Write(this.textEditorControl1.Text);
                    }
                }
            }
        }

    }
}
